<template>
  <div class="chart-data-container">
    <h2>功图数据</h2>
    <el-table :data="chartData" v-loading="loading" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="points" label="功图实际点数" width="150" />
      <el-table-column prop="times" label="功图采集时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.times) }}
        </template>
      </el-table-column>
      <el-table-column prop="x" label="X轴" />
      <el-table-column prop="y" label="Y轴" />
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination" style="margin-top: 20px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const chartData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleString()
}

// 获取功图数据
const fetchChartData = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch('/api/dashboard/chart', {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })

    if (!response.ok) {
      throw new Error('获取功图数据失败')
    }

    const result = await response.json()
    if (result.code === 200) {
      // 将数据转换为表格需要的格式
      const data = []
      const { points, times, x, y } = result.data
      const length = Math.max(
        points?.length || 0,
        times?.length || 0,
        x?.length || 0,
        y?.length || 0
      )

      for (let i = 0; i < length; i++) {
        data.push({
          points: points?.[i] || '',
          times: times?.[i] || '',
          x: x?.[i] || '',
          y: y?.[i] || ''
        })
      }

      chartData.value = data
      total.value = data.length
    } else {
      throw new Error(result.message || '获取功图数据失败')
    }
  } catch (error) {
    console.error('获取功图数据失败:', error)
    ElMessage.error(error.message)
  } finally {
    loading.value = false
  }
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchChartData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchChartData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchChartData()
})
</script>

<style scoped>
.chart-data-container {
  padding: 20px;
}
</style>
